<template>
    <template v-if="animation">
        <div v-if="loading" class="loading">
            加载中...
        </div>
        <template v-else>
            <div ref="inRef">
                <div>
                    <slot></slot>
                </div>
            </div>
            <div v-if="show" ref="outRef" class="print-container" :class="className"></div>
            <slot v-else></slot>
        </template>
    </template>
    <slot v-else></slot>
</template>

<script setup>
import { nextTick, onBeforeUnmount, onMounted, ref } from 'vue';
import Typed from 'typed.js';

const emit = defineEmits(['begin', 'complete']);
const props = defineProps({
    animation: {
        type: Boolean,
        default: false
    },
    className: {
        type: String,
        default: ''
    },
    startDelay: {
        type: Number,
        default: 0
    }
});
const show = ref(true);
const loading = ref(false);
const inRef = ref(null);
const outRef = ref(null);
let typedInstance = null;

const renderContent = () => {
    typedInstance = new Typed(outRef.value, {
        stringsElement: inRef.value,
        loop: false, //是否循环
        showCursor: false, //是否显示光标
        onBegin: () => {
            emit('begin');
        },
        onComplete: () => {
            show.value = false;
            emit('complete');
        }
    });
};

const init = () => {
    // 延迟执行
    if (props.startDelay > 0) {
        loading.value = true;
        setTimeout(() => {
            loading.value = false;
            nextTick(() => {
                renderContent();
            });
        }, props.startDelay);
    } else {
        renderContent();
    }
};
onMounted(() => {
    if (props.animation) {
        init();
    } else {
        // 没有动画，则直接完成
        emit('complete');
    }
});
onBeforeUnmount(() => {
    typedInstance && typedInstance.destroy();
});
</script>
<style lang="less" scoped>
.print-container {
    width: 100%;
}

@keyframes rotate-svg {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
}
.loading {
    height: 16px;
    :deep(svg) {
        animation: rotate-svg 0.8s linear infinite;
    }
}
</style>
